package com.szzg10.mina2.chapter2;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * NioSocketConnector
 * FilterChain
 * ConnectorFuture
 * IoSession
 *
 */
public class MinaTimeClient {

	public static final long CONNECT_TIMEOUT = 4000;
	public static final String HOSTNAME = "127.0.0.1";
	public static final int PORT = 9123;
	
	public static void main(String[] args) {
		
		NioSocketConnector connector = new NioSocketConnector();
		
		connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
		
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		
		connector.setHandler(new TimeClientHandler());
		
		ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
		future.awaitUninterruptibly();
		
		IoSession session = future.getSession();
		session.write("Hello!!!");
		
		session.getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}
}
